<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拍卖详情</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #fff9e6;
            margin: 0;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 20px;
        }

        .product-info {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .auction-info {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: sticky;
            top: 20px;
        }

        .image-gallery {
            margin-bottom: 20px;
        }

        .main-image {
            width: 100%;
            height: 400px;
            object-fit: contain;
            border-radius: 8px;
            margin-bottom: 10px;
        }

        .thumbnail-list {
            display: flex;
            gap: 10px;
            overflow-x: auto;
            padding-bottom: 10px;
        }

        .thumbnail {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 4px;
            cursor: pointer;
            border: 2px solid transparent;
            transition: all 0.3s ease;
        }

        .thumbnail:hover {
            border-color: #ffd700;
        }

        .thumbnail.active {
            border-color: #ffd700;
        }

        .product-title {
            font-size: 24px;
            color: #333;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .price-info {
            margin: 20px 0;
            padding: 15px;
            background: #fff9e6;
            border-radius: 8px;
            position: relative;
        }

        .current-price {
            font-size: 28px;
            color: #ff4d4f;
            font-weight: bold;
        }

        .original-price {
            color: #999;
            text-decoration: line-through;
            margin-left: 10px;
        }

        .bid-form {
            margin-top: 20px;
        }

        .bid-input {
            width: calc(100% - 24px);
            padding: 12px;
            border: 2px solid #ffd700;
            border-radius: 6px;
            margin-bottom: 10px;
            font-size: 16px;
            box-sizing: border-box;
        }

        .bid-btn {
            width: 100%;
            padding: 12px;
            background: #ffd700;
            border: none;
            border-radius: 6px;
            color: #8b4513;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .bid-btn:hover {
            background: #ffb700;
        }

        .bid-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .time-info {
            margin: 20px 0;
            text-align: center;
        }

        .countdown {
            font-size: 20px;
            color: #ff4d4f;
            font-weight: bold;
        }

        .bid-history {
            margin-top: 20px;
        }

        .bid-record {
            padding: 12px;
            border-bottom: 1px solid #eee;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .bid-record:last-child {
            border-bottom: none;
        }

        .status-tag {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 14px;
            margin-bottom: 10px;
        }

        .status-upcoming {
            background-color: #e6f7ff;
            color: #1890ff;
        }

        .status-ongoing {
            background-color: #f6ffed;
            color: #52c41a;
        }

        .status-ended {
            background-color: #fff1f0;
            color: #ff4d4f;
        }

        .product-details {
            margin-top: 20px;
            line-height: 1.6;
        }

        .seller-info {
            display: flex;
            align-items: center;
            padding: 15px;
            background: #fff;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
        }

        .seller-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            margin-right: 15px;
            cursor: pointer;
        }

        .seller-details {
            flex: 1;
        }

        .seller-name {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }

        .seller-credit {
            color: #666;
        }

        .credit-score {
            color: #ff6b6b;
            font-weight: bold;
        }

        .star-rating {
            color: #ffd700;
            margin-left: 5px;
        }

        .min-increment {
            color: #666;
            font-size: 14px;
            margin-top: 8px;
            padding: 4px 8px;
            background: #f5f5f5;
            border-radius: 4px;
            display: inline-block;
        }

        .bidder-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }

        .bid-info {
            flex: 1;
        }

        .bidder-name {
            font-weight: bold;
            color: #333;
            margin-bottom: 4px;
        }

        .bid-price {
            color: #ff4d4f;
            font-weight: bold;
        }

        .bid-time {
            color: #999;
            font-size: 12px;
        }

        .like-button {
            background: none;
            border: 2px solid #ff4d4f;
            border-radius: 20px;
            cursor: pointer;
            padding: 8px 16px;
            font-size: 16px;
            color: #ff4d4f;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .like-button.liked {
            background: #ff4d4f;
            color: white;
        }

        .like-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 8px rgba(255, 77, 79, 0.2);
        }

        .like-count {
            font-size: 14px;
            color: inherit;
        }

        .favorite-button {
            position: absolute;
            top: 15px;
            right: 15px;
            background: none;
            border: 2px solid #ffa940;
            border-radius: 20px;
            cursor: pointer;
            padding: 8px 16px;
            font-size: 14px;
            color: #ffa940;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .favorite-button.favorited {
            background: #ffa940;
            color: white;
        }

        .favorite-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 8px rgba(255, 169, 64, 0.2);
        }

        .favorite-button i {
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="product-info">
            <div class="seller-info" id="sellerInfo">
                <!-- 卖家信息将通过JavaScript动态加载 -->
            </div>
            
            <div class="image-gallery">
                <img src="" alt="商品主图" class="main-image" id="mainImage">
                <div class="thumbnail-list" id="thumbnailList">
                    <!-- 缩略图将通过JavaScript动态加载 -->
                </div>
            </div>
            <div class="product-title">
                <span id="productTitle"></span>
                <button class="like-button" onclick="toggleLike()">
                    <i class="fas fa-heart"></i>
                    <span class="like-count">0</span>
                </button>
            </div>
            <div class="product-details" id="productDetails"></div>
        </div>

        <div class="auction-info">
            <span id="statusTag" class="status-tag"></span>
            <div class="price-info">
                <div class="current-price">当前价格: ¥<span id="currentPrice">0.00</span></div>
                <div class="original-price">原价：¥<span id="originalPrice">0.00</span></div>
                <div class="min-increment">最小加价：¥<span id="minIncrement">0.00</span></div>
                <button class="favorite-button" onclick="addToFavorite()">
                    <i class="fas fa-star"></i>
                    <span>收藏商品</span>
                </button>
            </div>
            <div class="time-info">
                <div>距离结束还剩</div>
                <div class="countdown" id="countdown"></div>
            </div>
            <div class="bid-form">
                <input type="number" class="bid-input" id="bidAmount" placeholder="请输入出价金额">
                <button class="bid-btn" id="bidBtn" onclick="placeBid()">立即出价</button>
            </div>
            <div class="bid-history">
                <h3>出价记录</h3>
                <div id="bidRecords">
                    <!-- 出价记录将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        let auctionData = null;
        let countdownInterval = null;

        // 页面加载时获取拍信息
        $(document).ready(function() {
            const urlParams = new URLSearchParams(window.location.search);
            const auctionId = urlParams.get('id');
            if (auctionId) {
                loadAuctionDetail(auctionId);
            }

            // 加载收藏状态
            loadLikeStatus();
        });

        // 加载拍卖详情
        function loadAuctionDetail(id) {
            console.log('开始加载拍卖详情，ID:', id);
            $.ajax({
                url: `/auction/${id}`,
                type: 'GET',
                success: function(response) {
                    console.log('获取拍卖详情响应:', response);
                    if (response.state === 1) {
                        auctionData = response.data;
                        console.log('拍卖详情数据:', auctionData);
                        
                        // 添加浏览历史记录
                        $.ajax({
                            url: '/user/get-user',
                            type: 'GET',
                            success: function(userResponse) {
                                if (userResponse.state === 1) {
                                    const currentUserId = userResponse.data.id;
                                    const isSeller = currentUserId === parseInt(auctionData.sellerId);
                                    
                                    // 添加浏览历史记录
                                    $.ajax({
                                        url: '/history/add',
                                        type: 'POST',
                                        contentType: 'application/json',
                                        data: JSON.stringify({
                                            productId: auctionData.productId,
                                            productName: auctionData.productName,
                                            productPrice: auctionData.currentPrice,
                                            productImage: auctionData.productImage ? (typeof auctionData.productImage === 'string' ? JSON.parse(auctionData.productImage)[0] : auctionData.productImage[0]) : null,
                                            isAuction: true
                                        }),
                                        success: function(historyResponse) {
                                            console.log('浏览历史添加成功:', historyResponse);
                                        },
                                        error: function(err) {
                                            console.error('添加浏览历史失败:', err);
                                        }
                                    });
                                    
                                    if (isSeller) {
                                        // 如果是卖家，禁用出价按钮并显示提示
                                        $('#bidBtn').prop('disabled', true).text('不能参与自己的拍卖');
                                        $('#bidAmount').prop('disabled', true).attr('placeholder', '不能参与自己的拍卖');
                                    }
                                }
                                renderAuctionDetail();
                                startCountdown();
                                loadBidRecords();
                                // 检查收藏状态
                                checkFavoriteStatus();
                            }
                        });
                    } else {
                        console.error('加载拍卖信息失败:', response.msg);
                        alert('加载拍卖信息失败：' + response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('加载失败:', {
                        status: status,
                        error: error,
                        response: xhr.responseText
                    });
                    alert('加载失败，请稍后重试');
                }
            });
        }

        // 渲染拍卖详情
        function renderAuctionDetail() {
            console.log('开始渲染拍卖详情，数据:', auctionData);
            try {
                // 设置商品图片
                console.log('商品图片数据:', auctionData.productImage);
                const images = JSON.parse(auctionData.productImage || '[]');
                console.log('解析后的图片数组:', images);
                
                if (images.length > 0) {
                    $('#mainImage').attr('src', images[0]);
                    console.log('设置主图:', images[0]);
                } else {
                    console.warn('没有商品图片');
                    $('#mainImage').attr('src', 'img/default.png');
                }
                
                // 渲染缩略图
                const thumbnailList = $('#thumbnailList');
                thumbnailList.empty();
                images.forEach((image, index) => {
                    console.log(`渲染第${index + 1}张缩略图:`, image);
                    thumbnailList.append(`
                        <img src="${image}" 
                             class="thumbnail ${index === 0 ? 'active' : ''}" 
                             onclick="changeMainImage('${image}', this)">
                    `);
                });

                // 设置商品信息
                console.log('商品标题:', auctionData.productName);
                $('#productTitle').text(auctionData.productName);
                
                // 解析地址信息
                let locationInfo = '暂无地址';
                try {
                    if (auctionData.location) {
                        const locationObj = JSON.parse(auctionData.location);
                        console.log('解析的地址信息:', locationObj);
                        locationInfo = `${locationObj.province} ${locationObj.city} ${locationObj.district}`;
                    }
                } catch (e) {
                    console.error('解析地址信息失败:', e);
                }

                // 设置商品详情
                console.log('商品描述:', auctionData.productDescription);
                $('#productDetails').html(`
                    <p>${auctionData.productDescription || '暂无描述'}</p>
                    <p>品牌：${auctionData.brand || '未知'}</p>
                    <p>地址：${locationInfo}</p>
                    <p>出价次数：${auctionData.bidCount || 0}次</p>
                `);

                // 设置价格信息
                console.log('价格信息:', {
                    current: auctionData.currentPrice,
                    original: auctionData.originalPrice,
                    minIncrement: auctionData.minIncrement
                });
                $('#currentPrice').text(auctionData.currentPrice || '0.00');
                $('#originalPrice').text(auctionData.originalPrice || '0.00');
                $('#minIncrement').text(auctionData.minIncrement || '0.00');

                // 设置状态标签
                const status = getAuctionStatus();
                console.log('拍卖状态:', status);
                $('#statusTag').text(getStatusText(status))
                              .removeClass()
                              .addClass(`status-tag status-${status}`);

                // 设置出价按钮状态
                updateBidButtonState();
                
                // 修改卖家信息渲染部分
                console.log('卖家信息:', {
                    name: auctionData.sellerName,
                    avatar: auctionData.sellerAvatar,
                    creditScore: auctionData.sellerCreditScore
                });
                
                // 计算星级显示
                const creditScore = parseFloat(auctionData.sellerCreditScore) || 0;
                const starCount = Math.round(creditScore);
                const stars = '★'.repeat(starCount) + '☆'.repeat(5 - starCount);
                
                $('#sellerInfo').html(`
                    <img src="${auctionData.sellerAvatar || 'img/default-avatar.png'}" 
                         class="seller-avatar" 
                         onclick="window.location.href='/user-profile.html?id=${auctionData.sellerId}'"
                         alt="卖家头像">
                    <div class="seller-details">
                        <div class="seller-name">${auctionData.sellerName || '匿名卖家'}</div>
                        <div class="seller-credit">
                            信誉分：<span class="credit-score">${creditScore.toFixed(1)}</span>
                            <span class="star-rating">${stars}</span>
                        </div>
                    </div>
                `);

                // 检查收藏状态
                if (auctionData.productId) {
                    $.ajax({
                        url: `/favorite/check?productId=${auctionData.productId}`,
                        type: 'GET',
                        success: function(response) {
                            if (response.state === 1 && response.data) {
                                const $button = $('.favorite-button');
                                $button.addClass('favorited');
                                $button.html('<i class="fas fa-star"></i><span>已收藏</span>');
                            }
                        }
                    });
                }

            } catch (error) {
                console.error('渲染拍卖详情时发生错误:', error);
                alert('渲染商品信息失败，请刷新页面重试');
            }
        }

        // 切换主图
        function changeMainImage(src, thumbnail) {
            $('#mainImage').attr('src', src);
            $('.thumbnail').removeClass('active');
            $(thumbnail).addClass('active');
        }

        // 获取拍卖状态
        function getAuctionStatus() {
            const now = new Date().getTime();
            const start = new Date(auctionData.startTime);
            const end = new Date(auctionData.endTime);
            
            // 调整时区，将时间提前8小时
            start.setHours(start.getHours() - 8);
            end.setHours(end.getHours() - 8);
            
            if (now < start.getTime()) return 'upcoming';
            if (now > end.getTime()) return 'ended';
            return 'ongoing';
        }

        // 获取状态��本
        function getStatusText(status) {
            return {
                'upcoming': '即将开始',
                'ongoing': '正在进行',
                'ended': '已结束'
            }[status];
        }

        // 开始倒计时
        function startCountdown() {
            if (countdownInterval) {
                clearInterval(countdownInterval);
            }

            function updateCountdown() {
                const now = new Date().getTime();
                const start = new Date(auctionData.startTime);
                const end = new Date(auctionData.endTime);
                
                // 调整时区，将时间提前8小时
                start.setHours(start.getHours() - 8);
                end.setHours(end.getHours() - 8);
                
                const status = getAuctionStatus();
                
                let diff;
                let prefix;
                
                switch(status) {
                    case 'upcoming':
                        diff = start.getTime() - now;
                        prefix = '距开始还有';
                        break;
                    case 'ongoing':
                        diff = end.getTime() - now;
                        prefix = '距结束还有';
                        break;
                    case 'ended':
                        $('#countdown').text('已结束');
                        clearInterval(countdownInterval);
                        updateBidButtonState();
                        return;
                }

                const days = Math.floor(diff / (1000 * 60 * 60 * 24));
                const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((diff % (1000 * 60)) / 1000);

                $('#countdown').text(
                    `${prefix} ${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`
                );
            }

            updateCountdown();
            countdownInterval = setInterval(updateCountdown, 1000);
        }

        // 更新出价按钮状态
        function updateBidButtonState() {
            const status = getAuctionStatus();
            const bidBtn = $('#bidBtn');
            const bidInput = $('#bidAmount');
            
            console.log('更新出价按钮状态:', {
                status: status
            });
            
            if (status !== 'ongoing') {
                bidBtn.prop('disabled', true);
                bidInput.prop('disabled', true);
                bidBtn.text(status === 'upcoming' ? '未开始' : '已结束');
            } else {
                bidBtn.prop('disabled', false);
                bidInput.prop('disabled', false);
                bidBtn.text('立即出价');
            }
        }

        // 加载出价记录
        function loadBidRecords() {
            console.log('开始加载出价记录');
            $.ajax({
                url: `/auction/records/${auctionData.id}`,
                type: 'GET',
                success: function(response) {
                    console.log('获取出价记录响应:', response);
                    if (response.state === 1) {
                        console.log('出价记录数据:', response.data);
                        renderBidRecords(response.data);
                    } else {
                        console.error('加载出价记录失败:', response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('加载出价记录失败:', {
                        status: status,
                        error: error,
                        response: xhr.responseText
                    });
                }
            });
        }

        // 渲染出价记录
        function renderBidRecords(records) {
            const container = $('#bidRecords');
            container.empty();

            if (records.length === 0) {
                container.append('<div class="bid-record">暂无出价记录</div>');
                return;
            }

            records.forEach(record => {
                container.append(`
                    <div class="bid-record">
                        <img src="${record.userAvatar || 'img/default-avatar.png'}" 
                             class="bidder-avatar" 
                             alt="出价者头像">
                        <div class="bid-info">
                            <div class="bidder-name">${record.userName || '匿名用户'}</div>
                            <div class="bid-price">￥${record.bidPrice}</div>
                            <div class="bid-time">${new Date(record.createTime).toLocaleString()}</div>
                        </div>
                    </div>
                `);
            });
        }

        // 修改出价函数，添加卖家检查
        function placeBid() {
            const bidAmount = parseFloat($('#bidAmount').val());
            const currentPrice = parseFloat(auctionData.currentPrice);
            const minIncrement = parseFloat(auctionData.minIncrement);

            // 基本验证
            if (!bidAmount) {
                alert('请输入出价金额');
                return;
            }

            // 验证是否为卖家
            $.ajax({
                url: '/user/get-user',
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        const currentUserId = response.data.id;
                        if (currentUserId === parseInt(auctionData.sellerId)) {
                            alert('不能参与自己的拍卖');
                            return;
                        }
                        
                        // 验证出价是否合法
                        if (bidAmount <= currentPrice) {
                            alert('出价必须高于当前价格');
                            return;
                        }

                        if (bidAmount < currentPrice + minIncrement) {
                            alert(`最小加价幅度为 ¥${minIncrement}，出价需要大于 ¥${(currentPrice + minIncrement).toFixed(2)}`);
                            return;
                        }

                        // 再次验证拍卖状态
                        const status = getAuctionStatus();
                        if (status !== 'ongoing') {
                            alert('拍卖未开始或已结束');
                            return;
                        }

                        // 发送出价请求
                        $.ajax({
                            url: '/auction/bid',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify({
                                auctionId: auctionData.id,
                                bidPrice: bidAmount
                            }),
                            success: function(response) {
                                console.log('出价响应:', response);
                                if (response.state === 1) {
                                    alert('出价成功！');
                                    loadAuctionDetail(auctionData.id);
                                } else {
                                    alert('出价失败：' + response.msg);
                                }
                            },
                            error: function(xhr, status, error) {
                                console.error('出价请求失败:', {
                                    status: status,
                                    error: error,
                                    response: xhr.responseText
                                });
                                if (xhr.status === 401) {
                                    alert('请先登录');
                                } else {
                                    alert('出价失败，请稍后重试');
                                }
                            }
                        });
                    }
                }
            });
        }

        // 更新倒计时
        function updateCountdown(startTime, endTime) {
            const now = new Date();
            // 调整时区，将时间提前8小时
            const adjustedStartTime = new Date(startTime);
            adjustedStartTime.setHours(adjustedStartTime.getHours() - 8);
            const adjustedEndTime = new Date(endTime);
            adjustedEndTime.setHours(adjustedEndTime.getHours() - 8);
            
            if (now < adjustedStartTime) {
                // 未开始
                const diff = adjustedStartTime - now;
                const days = Math.floor(diff / (1000 * 60 * 60 * 24));
                const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((diff % (1000 * 60)) / 1000);
                
                $('#countdown').html(`距开始还有${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`);
                $('#bidButton').prop('disabled', true).text('未开始');
                return 0; // 未开始
            } else if (now > adjustedEndTime) {
                // 已结束
                $('#countdown').html('拍卖已结束');
                $('#bidButton').prop('disabled', true).text('已结束');
                return 2; // 已结束
            } else {
                // 进行中
                const diff = adjustedEndTime - now;
                const days = Math.floor(diff / (1000 * 60 * 60 * 24));
                const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                const seconds = Math.floor((diff % (1000 * 60)) / 1000);
                
                $('#countdown').html(`距结束还有${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`);
                $('#bidButton').prop('disabled', false).text('立即出价');
                return 1; // 进行中
            }
        }

        // 加载拍卖信息
        function loadAuctionInfo() {
            $.get(`/auction/${auctionId}`, function(response) {
                if (response.state === 1) {
                    const auction = response.data;
                    
                    // 更新页面信息
                    $('#productName').text(auction.productName);
                    $('#currentPrice').text(`¥${auction.currentPrice || auction.startPrice}`);
                    $('#originalPrice').text(`¥${auction.originalPrice}`);
                    $('#minIncrement').text(`¥${auction.minIncrement}`);
                    $('#brand').text(auction.brand);
                    $('#description').text(auction.productDescription);
                    
                    if (auction.location) {
                        const location = JSON.parse(auction.location);
                        $('#location').text(`${location.province} ${location.city} ${location.district}`);
                    }
                    
                    // 显示图片
                    if (auction.productImage) {
                        const images = JSON.parse(auction.productImage);
                        displayImages(images);
                    }
                    
                    // 更新拍卖状态和倒计时
                    auctionStatus = updateCountdown(auction.startTime, auction.endTime);
                    
                    // 加载出价记录
                    loadBidRecords();
                    
                    // 设置定时器，每秒更新倒计时
                    clearInterval(countdownTimer);
                    countdownTimer = setInterval(() => {
                        auctionStatus = updateCountdown(auction.startTime, auction.endTime);
                    }, 1000);
                    
                } else {
                    alert('加载拍卖信息��败：' + response.msg);
                }
            });
        }

        function loadLikeStatus() {
            const auctionId = getAuctionId();
            // 检查是否已收藏
            $.ajax({
                url: `/like/check?type=auction&id=${auctionId}`,
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        updateLikeButton(response.data.liked, response.data.likeCount);
                    }
                }
            });
        }

        function toggleLike() {
            const auctionId = getAuctionId();
            $.ajax({
                url: '/like/toggle',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    type: 'auction',
                    id: auctionId
                }),
                success: function(response) {
                    if (response.state === 1) {
                        updateLikeButton(response.data.liked, response.data.likeCount);
                    }
                }
            });
        }

        function updateLikeButton(liked, count) {
            const $likeButton = $('.like-button');
            if (liked) {
                $likeButton.addClass('liked');
            } else {
                $likeButton.removeClass('liked');
            }
            $('.like-count').text(count);
        }

        function getAuctionId() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('id');
        }

        // 检查收藏状态
        function checkFavoriteStatus() {
            if (!auctionData || !auctionData.productId) {
                console.error('商品ID不存在');
                return;
            }
            
            $.ajax({
                url: '/favorite/check',
                type: 'GET',
                data: {
                    productId: auctionData.productId
                },
                success: function(response) {
                    console.log('收藏状态检查响应:', response);
                    if (response.state === 1 && response.data) {
                        const $button = $('.favorite-button');
                        $button.addClass('favorited');
                        $button.html('<i class="fas fa-star"></i><span>已收藏</span>');
                    }
                },
                error: function(error) {
                    console.error('检查收藏状态失败:', error);
                }
            });
        }

        // 添加收藏功能
        function addToFavorite() {
            if (!auctionData || !auctionData.productId) {
                console.error('商品ID不存在');
                alert('商品信息不完整');
                return;
            }

            const $button = $('.favorite-button');
            const isFavorited = $button.hasClass('favorited');
            const url = isFavorited ? '/favorite/remove' : '/favorite/add';

            console.log(`${isFavorited ? '取消收藏' : '添加收藏'}，商品ID:`, auctionData.productId);
            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    productId: auctionData.productId
                },
                success: function(response) {
                    console.log('收藏响应:', response);
                    if (response.state === 1) {
                        if (isFavorited) {
                            $button.removeClass('favorited');
                            $button.html('<i class="fas fa-star"></i><span>收藏商品</span>');
                        } else {
                            $button.addClass('favorited');
                            $button.html('<i class="fas fa-star"></i><span>已收藏</span>');
                        }
                    } else {
                        alert(response.msg || (isFavorited ? '取消收藏失败' : '收藏失败'));
                    }
                },
                error: function(error) {
                    console.error('收藏请求失败:', error);
                    alert(isFavorited ? '取消收藏失败，请稍后重试' : '收藏失败，请稍后重试');
                }
            });
        }
    </script>
</body>
</html> 